// var abs = new verjs_select();

$(function () {
    getProvince();
    getCity('110000');
    // 有效时间
    $("#effectiveTime").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        startDate: new Date()
    });
    $('#fenpeiguize').css('display', 'none');
    loadCompanyListData();
    getCompany();

    $('form select:not(#companySelection)').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });
    $('.tagsinput').tagsinput({
        maxChars : 5,
        'maxTags': '5'
    });

});

// 渲染城市列表
function getProvince() {
    let provinceNames = [];
    $.each(cityJson[0], function (key, value) {
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    getCity('110000')
}

// 根据省获取市
function getCity(provinceId) {
    $('#city').html('');
    let key = '0,' + provinceId;
    let cityNames = [];
    $.each(cityJson[key], function (key, value) {
        cityNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#city').html(cityNames.join(''));
    $('#city').selectpicker('refresh');
}

// '切换城市'
function changeCity() {
    getCity($('#province').val());
}

// 有效时间
function yongjiu() {
    if ($('#yongJiu').prop('checked') == true) {
        $("#effectiveTime").prop('disabled', true);
        $("#effectiveTime").val("");
    } else {
        $("#effectiveTime").prop('disabled', false);
    }
}

// 切换分配方式
function changeWay(type) {
    if (type == 1) {
        $('.three').css('display', 'none');
        $('.one').css('display', 'block');
    }
    if (type == 2) {
        $('.one').css('display', 'none');
        $('.three').css('display', 'block');
        $('#companyList').selectpicker('refresh');
    }
}

// 池子
function seleceChi(type) {
    if (type == 2) {
        $('.branch-select').css('display', 'inline-block');
    } else {
        $('.branch-select').css('display', 'none');
        $('#companySelection').multiselect('deselectAll', false);
        $('#companySelection').multiselect('updateButtonText');
    }
}


/**
 * 被动分配人员名单功能
 * */
// 获取部门列表
function getCompany() {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            data.data.map(function (item) {
                optionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#companyList').html(optionHtml);
            // getPerson(data.data[0].companyId);
        }
    });
    // 部门改变更新人员列表
    $("select[id*='companyList']").on("change", function () {
        getPerson($(this).val());
    })
}
// 获取人员列表
function getPerson(companyId) {
    $.getJSON("/account/getAccountListByCompanyId?companyId=" + companyId, function (data) {
        if (data.code == '000000') {
            var optionPersonHtml = '';
            data.data.map(function (item) {
                optionPersonHtml += '<option value="' + item.accountId + '">' + item.userName + '</option>';
            });
            $('#personList').html(optionPersonHtml);
            $('#personList').selectpicker('refresh');
        }
    });
}
// 添加 被动分配人员名单
function addList() {
    var companyId = $('#companyList').val();
    var companyName = $('#companyList').find("option:selected").text();
    var personId = $('#personList').val();
    var personName = $('#personList').find("option:selected").text();

    // 判断是否为空
    if (companyId === '' || personId == '') {
        promptInfo('添加名单不能为空，请重新选择！');
        return false;
    }

    // 判断名单人员是否已添加
    for (var i = 0; i < $('#nameList li').length; i++) {
        if ($('#nameList li').eq(i).attr('data-company') === companyId && $('#nameList li').eq(i).attr('data-person') === personId) {
            promptInfo(personName + ' 已经添加到被动分配人员名单！');
            return false;
        }
    }

    var nameList = '<li data-company="' + companyId + '" data-person="' + personId + '"><span class="company">' + companyName + '</span><span class="person">' + personName + '</span><a href="JavaScript:void(0);"><i class="mdi mdi-close"></i></a></li>';
    $('#nameList ul').append(nameList);

    // 删除名单
    $('#nameList li a').on('click', function () {
        $(this).parents('li').remove();
    })
}


/**
 * 加载公司列表
 */
function loadCompanyListData() {
    $.ajax({
        url: "/company/getCompanyList",
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if (data) {
                if (data.code == '000000') {
                    // verSelect控件
                    // var selectDate = [];

                    // multiselect控件
                    var companyOption = '';

                    for (var i = 0, len = data.data.length; i < len; i++) {
                        // verSelect控件
                        /*var company = data.data[i];
                        var selectCompany = {};
                        selectCompany.id = company.companyId;
                        selectCompany.name = company.companyName;
                        selectDate.push(selectCompany);*/

                        // multiselect控件
                        companyOption += '<option value="' + data.data[i].companyId + '">' + data.data[i].companyName + '</option>'
                    }

                    $('#companySelection').html(companyOption).multiselect({
                        filterPlaceholder: '搜索',
                        enableFiltering: true,
                        includeSelectAllOption: true,
                        maxHeight: 300,
                        selectAllText: '全部选择',
                        nonSelectedText: '请选择',
                        nSelectedText: '已选择',
                        allSelectedText: '已选择全部',
                    });

                    // verSelect控件
                    /*abs.render({
                        elem: "#search",
                        data: selectDate,
                        init_value: [1],
                        body_height: 300,
                        checkbox: true,
                        name: "test"
                    });
                    $('#searchoption-list').css('z-index', 1000)*/
                } else {
                    promptInfo("查询所有公司失败");
                }

            }
        },
        error: function () {
            promptInfo('查询所有公司失败');
        }
    });
}

/**
 * 线索池提交按钮新增线索池
 */
function addPublicCluePool() {
    //线索池名称
    var cluePoolName = $.trim($("#cluePoolName").val());

    //省份id
    var provinceId = $('#province').val();

    //省份名称
    var provinceName = $("#province").find("option:selected").text();

    //城市id
    var cityId = $('#city').val();

    //城市名称
    var cityName = $("#city").find("option:selected").text();

    //行业
    var industry = $("#industry").val();

    //来源
    var source = $("#source").val();

    //是否永久有效
    var permanent = "";
    if ($('#yongJiu').is(':checked')) {
        permanent = 1;
    } else {
        permanent = 0;
    }

    //有效时间
    var effectiveTime = $('#effectiveTime').val();

    //线索池分配方式
    var allocation = $("input[name='allocation']:checked").val();

    //容量
    var capacity = $("#capacity").val();

    //性质
    var nature = $("input[name='nature']:checked").val();

    //转换方式
    var conversionMethod = $("input[name='conversionMethod']:checked").val();

    var tagStr = $('.tagsinput').val().split(' ').join(',');
    var tagStrNew = tagStr.substring(0, tagStr.lastIndexOf(',')) + tagStr.substring(tagStr.lastIndexOf(',') + 1);
    //线索池标签
    var tag = tagStrNew;

    //线索池类型
    var poolType = $('#poolType').val();

    //公司id
    // verSelect控件
    /*var selectCompany = [];
    selectCompany = abs.get_value('search');
    var companyIdList = [];
    for (let i = 0; i < selectCompany.length; i++) {
        companyIdList.push(selectCompany[i].id);
    }*/
    var companyIdList = $('#companySelection').val();


    //无跟进退回时间间隔
    var returnInterval = $("#returnInterval").val();

    //最多领取数量
    var maximumNumber = $("#maximumNumber").val();

    //同一线索不能连续领取间隔
    var timeInterval = $("#timeInterval").val();

    //任意线索不能连续领取间隔
    var continueTimeInterval = $("#continueTimeInterval").val();

    //分配数量
    var assignedQuantity = $("#assignedQuantity").val();

    //分配时间间隔
    var allocationTimeInterval = $("#allocationTimeInterval").val();

    //分配人员名单
    var assignedPersonList = [];
    //选择的审批人
    for (let i = 1; i < $('#nameList li').length; i++) {
        let obj = {};
        obj.companyId = $('#nameList li').eq(i).attr('data-company');
        obj.peopleId = $('#nameList li').eq(i).attr('data-person');
        assignedPersonList.push(obj)
    }

    //线索池名称为空和长度验证
    if (!cluePoolName) {
        promptInfo("线索池名称不能为空!");
        return;
    } else {
        if (cluePoolName.length > 20) {
            promptInfo("线索池名称长度不能大于20个字！");
            return;
        }
    }

    //所在行业
    if (!industry) {
        promptInfo("所在行业不能为空!");
        return;
    }

    //有效时间判断
    if (permanent == 0 && $.trim(effectiveTime) == "") {
        promptInfo("请选择有效时间！");
        return;
    }

    //标签为空判断
    if (!tag) {
        promptInfo("标签不能为空！");
        return;
    }

    //线索池容量判断
    if (!capacity) {
        promptInfo("线索池容量不能为空！");
        return;
    }

    //线索池分配方式
    if (!allocation) {
        promptInfo("分配方式必选！");
        return;
    }

    //线索池性质
    if (!nature) {
        promptInfo("线索池性质必选！");
        return;
    }

    //如果是被动领取并且最多领取数量为空
    if ((allocation == 1 && !maximumNumber) || (allocation == 3 && !maximumNumber)) {
        promptInfo("最多领取数量必填！");
        return;
    }

    //如果是被动领取并且最多领取数量为空
    if ((allocation == 1 && !collectionTimeInterval) || (allocation == 3 && !collectionTimeInterval)) {
        promptInfo("最多领取数领取时间间隔必填！");
        return;
    }

    //无跟进时间间隔验证
    if (!returnInterval) {
        promptInfo("无跟进退回时间间隔必填！");
        return;
    }

    //如果是被动分配并且分配时间间隔为空
    if ((allocation == 2 && !allocationTimeInterval) || (allocation == 3 && !allocationTimeInterval)) {
        promptInfo("分配时间间隔必填！");
        return;
    }

    //如果是被动分配并且分配时间间隔为空
    if ((allocation == 2 && !assignedQuantity) || (allocation == 3 && !assignedQuantity)) {
        promptInfo("分配数量必填！");
        return;
    }

    var jsonData = {
        "cluePoolName": cluePoolName,
        "provinceId": provinceId,
        "provinceName": provinceName,
        "cityId": cityId,
        "cityName": cityName,
        "industry": industry,
        "source": source,
        "permanent": permanent,
        "effectiveTime": effectiveTime,
        "allocation": allocation,
        "capacity": capacity,
        "nature": nature,
        "conversionMethod": conversionMethod,
        "tag": tag,
        "poolType": poolType,
        "companyIdList": companyIdList,
        "returnInterval": returnInterval,
        "maximumNumber": maximumNumber,
        "collectionTimeInterval": timeInterval,
        "continueTimeInterval": continueTimeInterval,
        "assignedQuantity": assignedQuantity,
        "allocationTimeInterval": allocationTimeInterval,
        "assignedPersonList": assignedPersonList

    };

    $.ajax({
        url: '/cluePoolPublic/addCluePoolPublic',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("线索池表单", "/front/cluePoolManager/cluePoolForm");

                                // 提交完表单，重新加载相关table列表页面
                                refreshActivePane('/front/cluePoolManager/cluePoolForm');

                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            } else if (data.code == "C00010") {
                $.alert("线索池名称重复！");
            } else {
                $.alert("保存失败！");
            }
        }),
        error: (function (res) {
            $.alert("保存失败！");
        })
    });
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

/**
 * 表单重置功能
 *
 * */
function formReset() {
    $('form')[0].reset();
    $('form').find('select').selectpicker('refresh');
    $('#staticPath2').val('');
    $('.words-split').html('');
    $('#nameList ul').empty();
    changeWay(1);
}